package com.spider.moudle.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.spider.moudle.entity.Area;
import com.spider.moudle.entity.Setting;
import com.spider.moudle.entity.WebType;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Linbo Hu on 2017/11/27.
 * 获取site的个性化配置
 */
public class SettingsUtil {


    private static JSONObject object = null;

    private static Map<String, JSONObject> map = new ConcurrentHashMap<>();

    private static List<JSONObject> list = new Vector<>();

    private static Map<String, Setting> settingMap = new ConcurrentHashMap<>();

    private static List<Setting> settingList = new ArrayList<>();

    static {
        InputStream inputStream = null;
        try {

            File file=new File("settings.json");
            if(!file.exists()){
                String prePath=PropertiesUtil.getClassPath().split("!")[0];
                String fileP=prePath.substring(6,prePath.length()-10)+"/"+"settings.json";
                file=new File(fileP);
            }
            object = JSON.parseObject(IOUtils.toString(new FileInputStream(file), Charset.forName("UTF-8")));
            JSONArray array = object.getJSONArray("settings");
            for(int i = 0; i < array.size(); i++) {
                JSONObject object = array.getJSONObject(i);
                String type = object.getString("type");
                WebType webType = null;
                if("forum".equals(type)) {
                    webType = WebType.FORLUM;
                } else if("news".equals(type)) {
                    webType = WebType.NEWS;
                } else if("weibo".equals(type)) {
                    webType = WebType.WEIBO;
                } else if("weixin".equals(type)) {
                    webType = WebType.WEIXIN;
                } else if("qqzone".equals(type)) {
                    webType = WebType.QQZONE;
                } else {
                    System.err.println("未知的webtype");
                }
                JSONArray site_array = object.getJSONArray("sites");
                for(int j = 0; j < site_array.size(); j++) {
                    JSONObject site_object = site_array.getJSONObject(j);
                    map.put(site_object.getString("site"), site_object);
                    list.add(site_object);
                    Setting setting = new Setting();
                    setting.setSite(site_object.getString("site"));
                    setting.setName(site_object.getString("name"));
                    setting.setIndex(site_object.getString("index"));
                    setting.setCrawler_num(site_object.getInteger("crawler_num"));
                    setting.setInterval_minutes(site_object.getInteger("interval_minutes"));
                    setting.setSpeech_task(site_object.getString("speech_task"));
                    setting.setSpeech_work_count(site_object.getInteger("speech_work_count"));
                    setting.setUser_task(site_object.getString("user_task"));
                    setting.setUser_work_count(site_object.getInteger("user_work_count"));
                    setting.setMax_page_count(site_object.getInteger("max_page_count"));
                    setting.setCrawler_class_path(site_object.getString("crawler_class_path"));
                    setting.setSpider_is_worked(site_object.getBoolean("spider_is_worked"));
                    setting.setTask_thread_count(site_object.getInteger("task_thread_count"));
                    setting.setReply_thread_count(site_object.getInteger("reply_thread_count"));
                    setting.setWeb_type(webType);
                    settingMap.put(site_object.getString("site"), setting);
                    settingList.add(setting);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取所有的site
     * @return
     */
    public static List<JSONObject> getAllSiteList() {
        return list;
    }




    /**
     * 获取所有的site
     * @return
     */
    public static Map<String, JSONObject> getAllSiteMap() {
        return map;
    }

    /**
     * 获取所有的setting
     * @return
     */
    public static Map<String, Setting> getSettingMap() {
        return settingMap;
    }

    /**
     * 获取所有的setting
     * @return
     */
    public static List<Setting> getAllSettingList() {
        return settingList;
    }


    /**
     * 根据site获取某个网站的配置
     * @param site
     * @return
     */
    public static Setting getSettingBySite(String site) {
        return settingMap.get(site);
    }


    /**
     * 根据site类型和site名称获取某个site的个性化配置
     * @param type
     * @param site
     * @return
     */
    public static JSONObject loadConfig(String type, String site) {
        if(object == null) {
            System.err.println("获取settings.json文件失败");
            return null;
        }
        JSONArray array = (JSONArray) JSONPath.eval(object, "$.settings[type = '"+ type +"']");
        JSONArray site_array = (JSONArray)JSONPath.eval(array, "$.sites[site = '"+ site +"']");
        if(site_array.isEmpty()) {
            System.err.println("在type为" + type + "的setting中未获取到site为" + site + "的数据!");
            return null;
        }
        return site_array.getJSONObject(0);
    }

    public static void main(String[] args) throws Exception {
        //JSONObject config = SettingsUtil.loadConfig("forum", "TianYa");
        //System.out.println(config.getString("name"));
        //getAllTopic();
        //System.out.println(getSettingList());

        System.out.println(getSettingBySite("TianYa"));
    }
}
